<template>
  <el-form
    v-if="visible"
    ref="filterForm"
    inline
    size="small"
    class="filter-container"
    @submit.native.prevent
  >
    <el-form-item
      v-if="scopes.length"
      label="scope"
      prop="scope"
    >
      <el-select
        v-model="scope"
        collapse-tags
        clearable
        :placeholder="'请选择'"
        @change="handleFilter"
      >
        <el-option
          v-for="option in scopes"
          :key="option.id"
          :label="option.name"
          :value="option.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item prop="keyword">
      <el-input
        v-model="keyword"
        :placeholder="placeholder"
        class="input-button-suffix"
        @keyup.enter.native="handleFilter"
      >
        <el-button
          slot="suffix"
          type="text"
          icon="el-icon-search"
          @click="handleFilter"
        />
      </el-input>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'KeywordSearch',
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '输入关键词检索'
    },
    name: {
      type: String,
      default: 'keyword'
    },
    value: {
      type: Object,
      default: null
    },
    scopes: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      scope: '',
      keyword: '',
      filterModel: {
        scope: '',
        keyword: ''
      }
    }
  },
  computed: {
    filterParams: {
      get() {
        return this.value
      },
      set(v) {
        this.value = v
      }
    },
    defaultScope() {
      if (this.scopes.length > 0) {
        var defaultScope =
          this.scopes.find(item => {
            return !!item.default
          }) || this.scopes[0]
        return defaultScope && defaultScope.id
      }
      return ''
    },
    scopeFilter() {
      var p = {}
      var key = this.scope || this.name || 'keyword'
      p[key] = this.keyword
      return p
    }
  },
  mounted() {
    this.scope = this.defaultScope
  },
  methods: {
    handleFilter() {
      console.log(this.scopeFilter)
      this.$emit('input', this.scopeFilter)
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  .el-input {
    width: 100% !important;
  }
  .el-select {
    width: 100% !important;
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
